package com.renwei.yunlong.activity.work;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.ImageFileAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.UpdateUserIconBean;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.UploadManger;
import com.renwei.yunlong.view.SimpleOptionView;
import com.renwei.yunlong.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;


/**
 * 工单 - 投诉
 * <p>
 * Created by Administrator on 2017/8/29.
 */

public class WorkComplaintsActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, InvokeListener, TakePhoto.TakeResultListener, ImageFileAdapter.OnItemDeleteClickListener, AdapterView.OnItemClickListener, TextWatcher {


    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.tv_input_title)
    TextView tvInputTitle;
    @Bind(R.id.et_input_content)
    EditText etInputContent;
    @Bind(R.id.tv_input_number)
    TextView tvInputNumber;
    @Bind(R.id.grid_view)
    GridView gridView;
    @Bind(R.id.btn_confirm)
    Button btnConfirm;
    private TakePhoto takePhoto;
    private PromptDialog promptDialog;
    private ImageFileAdapter adapter;
    private InvokeParam invokeParam;
    private Uri temmImageUrl;
    private File newFile = null;
    private String requestId = "";
    private List<UpdateUserIconBean> photos = new ArrayList<>();
    private ArrayList<TImage> list;
    private int limt;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complaints);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        getTakePhoto().onCreate(savedInstanceState);
        initData();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        getTakePhoto().onSaveInstanceState(outState);
    }

    private void initData() {
        simpleTileView.setTitle("投诉");
        btnConfirm.setOnClickListener(this);
        promptDialog = new PromptDialog(this);
        tvInputTitle.setText("投诉内容(必填)");
        etInputContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100), AppHelper.emojiFilter});
        etInputContent.addTextChangedListener(this);
        requestId = getIntent().getStringExtra("requestId");
        // 上传附件图片
        adapter = new ImageFileAdapter(this);
        adapter.setOnItemDeleteClickListener(this);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        configCompress(takePhoto);
        return takePhoto;
    }

    //配置图像压缩相关
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxSize(1024000)
                .create();
        config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_confirm:
                String content = etInputContent.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    showCenterInfoMsg("请输入投诉内容");
                    return;
                }

                // 图片上传
                String filenames = "";
                String attachPath = "";
                String attachSize = "";
                for (UpdateUserIconBean photo : photos) {
                    filenames += photo.getName() + ",";
                    attachPath += photo.getPath() + ",";
                    attachSize += photo.getSize() + ",";
                }
                if (!TextUtils.isEmpty(filenames)) {
                    filenames = filenames.substring(0, filenames.length() - 1);
                }
                if (!TextUtils.isEmpty(attachPath)) {
                    attachPath = attachPath.substring(0, attachPath.length() - 1);
                }
                if (!TextUtils.isEmpty(attachSize)) {
                    attachSize = attachSize.substring(0, attachSize.length() - 1);
                }

                HashMap<String, String> map = new HashMap<>();
                if ("1".equals(companyType)) {
                    map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                } else if ("2".equals(companyType)) {
                    map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                }
                map.put("requestIds", requestId);
                map.put("complainDetail", content);
                map.put("attachPath", attachPath);
                map.put("attachSize", attachSize);
                map.put("filenames", filenames);

                ServiceRequestManager.getManager().setWorkComplain(this, JsonMapUtil.mapToJson(map), this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onDeleteClick(int position) {
        adapter.deleteItem(position);
        photos.remove(position);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int length = s.length();
        tvInputNumber.setText(length + "");
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                EventBus.getDefault().post(new WorkPageRefreshEvent());
                CommonBean complainBean = new Gson().fromJson(result, CommonBean.class);
                if (complainBean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("操作成功");
                    finish();
                } else {
                    showCenterInfoMsg(complainBean.getMessage().getMessage());
                }
                break;
            case 999: //上传
                UpdateUserIconBean bean = new Gson().fromJson(result, UpdateUserIconBean.class);
                photos.add(bean);
                for (TImage image : list) {
                    String image2Name = new File(image.getCompressPath()).getName();
                    if (image2Name.equals(bean.getName())) {
                        adapter.addItem(image.getCompressPath());
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }


    @Override
    public void takeSuccess(TResult result) {
        try {
            list = result.getImages();
            for (TImage it : list) {
                newFile = new File(it.getCompressPath());
                if (newFile.exists()) {
                    UploadManger manger = UploadManger.getManager();
                    if ("1".equals(companyType)) {
                        manger.uploadIcon(mContext, newFile, this, ownerBean.getRows().getCompany().getVersionCode()
                                , ownerBean.getRows().getCompany().getCompanyCode());
                    } else if ("2".equals(companyType)) {
                        manger.uploadIcon(mContext, newFile, this, serviceLoginBean.getRows().getCompany().getVersionCode()
                                , serviceLoginBean.getRows().getCompany().getCompanyCode());
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            showCenterInfoMsg(this.getString(R.string.tip_file_is_not_exist));
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }


    public static void OpenActivity(Context context, String requestId) {
        Intent i = new Intent(context, WorkComplaintsActivity.class);
        i.putExtra("requestId", requestId);
        context.startActivity(i);
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (position == (adapter.getmList() == null ? 0 : adapter.getmList().size())) { // 获取本地文件
            limt = 10 - (adapter.getCount() - 1);
            if (limt > 0) {
                PromptButton cancle = new PromptButton("取消", null);
                File file = new File(getApplication().getCacheDir(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                temmImageUrl = Uri.fromFile(file);
                LogUtil.e("imageUri " + temmImageUrl.toString());
                promptDialog.showAlertSheet("", true, cancle,
                        new PromptButton("打开相册", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickMultiple(limt);
                               // showTopWrongMsg("当前还可以选择" + limt + "张图片附件");
                            }
                        }), new PromptButton("拍照", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickFromCapture(temmImageUrl);
                            }
                        }));
            } else {
                showTopWrongMsg("最多只能选择10张");
            }
        } else {
            ArrayList<String> list = new ArrayList<>();
            list.addAll(adapter.getmList());
            PhotoDisplayActivity.OpenActivity(mContext, list, position);
        }
    }

}
